import numpy as np
import cv2
from matplotlib import pyplot as plt

#img1=cv2.imread('../misc_pic/manowar_logo.jpg',cv2.IMREAD_GRAYSCALE)
#img2=cv2.imread('../misc_pic/manowar_cd.jpg',cv2.IMREAD_GRAYSCALE)

img1=cv2.imread('../chess_pic/left01.jpg',cv2.IMREAD_GRAYSCALE)
img2=cv2.imread('../chess_pic/left02.jpg',cv2.IMREAD_GRAYSCALE)

orb=cv2.ORB_create()
kp1,des1=orb.detectAndCompute(img1,None)    #检测并计算图像1的特征
kp2,des2=orb.detectAndCompute(img2,None)    #检测并计算图像2的特征
bf=cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck=False)  #创建Brute Force匹配器

FLANN_INDEX_LSH=6
indexParams= dict(algorithm = FLANN_INDEX_LSH,
                   table_number = 6, # 12
                   key_size = 12,     # 20
                   multi_probe_level = 1) #2
searchParams=dict(checks=50)    #
flann=cv2.FlannBasedMatcher(indexParams,searchParams)   #创建FLANN匹配器
#进行匹配操作
#matches=flann.knnMatch(des1,des2,k=3)

"""match返回最好的匹配"""
matches=bf.match(des1,des2)
matches=sorted(matches,key=lambda x:x.distance)
img3=cv2.drawMatches(img1,kp1,img2,kp2,matches[:8],img2,flags=2)

"""knnMatch返回k个匹配，这样就可以滤除除特别条件外的匹配"""
#matches=bf.knnMatch(des1,des2,k=2)  #当k>1时，bf的crossCheck须为False

#img3=cv2.drawMatchesKnn(img1,kp1,img2,kp2,matches,img2,flags=2)

plt.imshow(img3),plt.show()

while(True):
    if cv2.waitKey() & 0xff ==ord("q"):
        break
cv2.destroyAllWindows()